# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 14:55:43 2013

@author: aponteeduarddo@gmail.com
Copyright Eduardo Aponte 2013.
"""

from mex_binder import binder_py

mx_open_eyelink_system = binder_py('mx_open_eyelink_system')
mx_open_eyelink_system.mx_c.headers = ['<eyelink.h>','"mex.h"','"utils.h"']
mx_open_eyelink_system.bindo += ['utils.o']
mx_open_eyelink_system.mx_c.code = '''

INT16 _main( INT16 bs, char FARTYPE *ops )
{
    return open_eyelink_system(bs,ops); 
}


void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
    mwSize td[2] = {1,1};
    double *status;
    int i;
    /* Buffer size */
    int bs; 
    /* Matlab buffer: WARNING no protection against buffer over load */
    char *mb;
    /* Eyelink char. To support compatibility.*/
    char FARTYPE *elb;
    
    
    /* Verify input arguments. */
    if(nrhs != 2 ) {
        mexErrMsgTxt("Incorrect number of inputs.");
    } else if( nlhs > 1 ) {
        mexErrMsgTxt("Too many output arguments.");
    }
    
    if ( isscalar( *prhs ) ){
        INT16 scalar;
        /* Returns the scalar, casts to int if necessary. Returns 0 if */
        /* input is complex. */
        if ( returnscalar( *prhs, &bs ) != 1 )
            mexErrMsgTxt("Complex data is not supported.");                        
    } else {
        mexErrMsgTxt("bufsize should be a scalar."); 
    }
    
    if ( mxIsChar(prhs[1]) != 1)
      mexErrMsgTxt( "options must be a string.");
      
    mb  = mxArrayToString(prhs[1]);
    
    if(mb == NULL) 
      mexErrMsgTxt("Could not convert input to string.");
    
    bs  = (mxGetM(*prhs) * mxGetN(*prhs)) + 1;
    elb = mxCalloc(bs,sizeof(char FARTYPE));    
    
    for (i = 0; i < bs-1; i++)
        elb[i] = (char FARTYPE ) mb[i];
    
    plhs[0] = mxCreateNumericArray( 2, td, mxDOUBLE_CLASS, mxREAL);
    status = mxGetPr(plhs[0]);    
    status[0] = (double ) _main( (INT16 ) bs, elb );
    
    mxFree( elb );
    
    return;
    
}


'''

mx_open_eyelink_system.mx_c.mdoc = \
'''function [ status ] = mx_open_eyelink_system( bufsize, options )
%MX_OPEN_EYELINK_SYSTEM Use this function to initialize the EyeLink library.
%
% This will also start the millisecond clock. No connection is attempted to 
% the eyetracker yet. It is preferable to call open_eyelink_connection(-1) 
% instead, as this prepares other parts of the DLL for use.
%
% Remarks:
% MUST BE FIRST CALL TO LINK INTERFACE.
% Parameters:
% bufsize 	Size of sample buffer. 60000 is the maximum allowed. (0 for default)
% options 	Text specifying initialization options. Currently no options are supported. (NULL or "" for defaults)
% Returns:
% 0 if failed, nonzero (-1 or TSR SWI number) if success.
%
'''
mx_open_eyelink_system.write_c()
mx_open_eyelink_system.write_m()
mx_open_eyelink_system.compile()
mx_open_eyelink_system.write_sh()

